package com.jww.service.impl;

import com.github.pagehelper.PageHelper;
import com.jww.domain.system.User;
import com.jww.mapper.system.UserMapper;
import com.jww.service.UserService;
import com.jww.utils.MyUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.UUID;

public class UserServiceImpl implements UserService {

    @Override
    public List<User> selectAll(String pageNum, String pageSize) {
        SqlSession sqlSession = MyUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        int num=1;
        int count=5;
        if (pageNum!=null){
            num=Integer.parseInt(pageNum);
        }

        if (pageSize!=null){
            count=Integer.parseInt(pageSize);
        }

        PageHelper.startPage(num,count);

        List<User> list = mapper.selectAll();
        MyUtils.close(sqlSession);
        return list;
    }

    @Override
    public List<User> list() {
        SqlSession sqlSession = MyUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = mapper.selectAll();
        MyUtils.close(sqlSession);
        return list;
    }

    @Override
    public void save(User user) {
        SqlSession sqlSession = MyUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        mapper.save(user);
        MyUtils.close(sqlSession);
    }

    @Override
    public boolean delete(String ids) {
        SqlSession sqlSession =null;
        boolean flag=false;
        try {
            sqlSession = MyUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            String[] idss = ids.split(",");
            mapper.delete(idss);
            MyUtils.close(sqlSession);
            flag=true;
        }catch (Exception e){
            throw new RuntimeException("删除失败");
        }finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
        }
        return flag;
    }

    @Override
    public User selectById(String id) {
        SqlSession sqlSession = MyUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectById(id);
        MyUtils.close(sqlSession);
        return user;
    }

    @Override
    public void update(User user) {
        SqlSession sqlSession = MyUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.update(user);
        MyUtils.close(sqlSession);
    }
}
